import {
  Controller,
  Body,
  Param,
  Headers,
  Get,
  Post,
  Put,
  Delete,
  HttpException,
} from '@nestjs/common';
import * as crypto from 'crypto';
import * as jwt from 'jsonwebtoken';
import { UserService } from './user.service';
import { UserEntity } from './user.entity';
import { CreateUserDto, LoginUserDto, UpdateUserDto } from './user.dto';
import { SECRET } from '../config';

@Controller('users')
export class UserController {
  constructor(private readonly userService: UserService) {}

  @Get('user')
  async findMe(
    @Headers('authorization') authorization: string,
  ): Promise<UserEntity> {
    const token = authorization.split(' ')[1];
    const decoded: any = jwt.verify(token, SECRET);
    const user = await this.userService.findById(decoded.id);
    return user;
  }

  @Put('users')
  async update(@Param('authorization') authorization, @Body('user') userData: UpdateUserDto) {
    const token = authorization.split(' ')[1];
    const decode: any = jwt.verify(token, SECRET);
    // Todo: 标题更新之后需要更新slug
    return this.userService.update(decode.id, userData);
  }

  @Post('users')
  async create(@Body('user') userData: CreateUserDto) {
    return this.userService.creat(userData);
  }

  @Delete('users/:slug')
  async delete(@Param() params) {
    return this.userService.delete(params.slug);
  }

  @Post('users/login')
  async login(@Body('user') userLoginData: LoginUserDto): Promise<string> {
    const user = await this.userService.findOne({
      email: userLoginData.email,
      password: crypto
        .createHmac('sha256', userLoginData.password)
        .digest('hex'),
    });
    if (!user) throw new HttpException('User not found', 401);

    const payload = {
      id: user.id,
      username: user.username,
      email: user.email,
    };
    return await this.userService.generateJWT(payload);
  }
}
